<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          功能名称:
          <NInput placeholder="输入功能名称" v-model:value="paginationReactive.functionName" clearable />
          <NButton type="primary" ghost @click="queryTableData(true)">
            查询
          </NButton>
        </NSpace>
        <NSpace align="center">
          <NButton type="primary" style="width: 115px" @click="$router.push({ path: '/OA/ProgressSetting/ProgressAdd' })">
            新增流程
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" :title="title">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ dialogContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { NButton, NDataTable, NPagination, useMessage, NSpace, NInput, NModal } from 'naive-ui'
import { h, ref, reactive, onMounted, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { DataTableColumns } from 'naive-ui'
import type { HttpResponse } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useViewerStore } from '@/views/OA/Common/store'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '序号',
    key: 'orderIndex',
    width: '20',
    align: useStore.isCenter,
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    }
  },
  {
    title: '绑定功能',
    key: 'functionName',
    width: '30',
    align: useStore.isCenter
  },
  {
    title: '流程名称',
    key: 'entityName',
    width: '40',
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'entityStatusFlag',
    width: '20',
    align: useStore.isCenter,
    render(e) {
      return e.entityStatusFlag ? '启用' : '禁用'
    }
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: '30',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            router.push({
              path: '/OA/ProgressSetting/ProgressUpdate',
              query: { id: e.id }
            })
          }
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            title.value = '流程复制提示'
            dialogContent.value = '您确定要复制该条流程吗？'
            progressId.value = e.id
            contentVisible.value = true
          }
        },
        {
          default: () => '复制'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          color: useStore.color['delete'],
          onClick: () => {
            title.value = '删除提示'
            dialogContent.value = '您确定要删除该条流程吗？'
            progressId.value = e.id
            contentVisible.value = true
          }
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  functionName: null, //标题
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
//绑定信息
const parentCodeList: any = ref([])
const getFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'progress',
    api: 'getWorkFlowFunctionCodeList',
  })
  if (error) return message.error(error.message)
  parentCodeList.value = res.data
}
//复制
const handleCopy = async () => {
  tableLoading.value = true
  contentVisible.value = false
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'progress',
    api: 'progressCopy',
    uri: {
      id: progressId.value
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success('复制成功')
  queryTableData(true)
}
// 删除
const handleDelete = async () => {
  tableLoading.value = true
  contentVisible.value = false
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'progress',
    api: 'progressDelete',
    override: {
      data: [progressId.value]
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success('删除成功')
  queryTableData(true)
}
// 提交
const title = ref()
const dialogContent = ref()
const contentVisible = ref(false)
const progressId = ref()
const submit = () => {
  if (title.value == '删除提示') return handleDelete()
  handleCopy()
}
//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'progress',
    api: 'progressList',
    override: {
      params: {
        functionName: paginationReactive.functionName,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  paginationReactive.itemCount = res.data?.totalCount
  tableData.value = res.data?.list
}

onMounted(() => {
  getFunction()
})

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1, queryTableData())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/ProgressSetting/progress') {
      queryTableData()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
